import axios, { RawAxiosRequestHeaders, ResponseType } from "axios";
import qs from "qs";
import {
  requestUseSucc,
  requestUseError,
  headers,
  responseUseSucc,
  responseUseError,
} from "./common";

const instance = axios.create({
  // baseURL: path,
  timeout: 600000,
  headers: headers,
  paramsSerializer: (params) => qs.stringify(params, { indices: false }),
});
//请求拦截
instance.interceptors.request.use(requestUseSucc, requestUseError);
//响应拦截
instance.interceptors.response.use(responseUseSucc, responseUseError);

// 参数类型改为泛型
export default {
  get: <T>(url: string, data = {}, responseType: any = "json"): Promise<T> => {
    return instance({
      url,
      method: "get",
      params: data,
      responseType: responseType,
    }) as Promise<T>;
  },
  post: <T>(
    url: string,
    data = {},
    headers?: RawAxiosRequestHeaders,
    responseType?: ResponseType
  ): Promise<T> => {
    return instance({
      url,
      method: "post",
      data: data,
      headers,
      responseType,
    }) as Promise<T>;
  },
  put: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "put", data: data }) as Promise<T>;
  },
  delete: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "delete", data: data }) as Promise<T>;
  },
  postFile: <T>(url: string, data = {}, config: any): Promise<T> => {
    return instance({
      url,
      method: "post",
      data: data,
      ...config,
    }) as Promise<T>;
  },
};
